package unicall.em.utils;

import java.io.ByteArrayInputStream;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;

public class AWSUtil {
   
    private final static Logger logger = LogUtil.getInstance(AWSUtil.class);
    
    public static AmazonS3 getS3Client(){
        AWSCredentials credentials = new BasicAWSCredentials(Constant.AWS_ACCESS_KEY, Constant.AWS_SECRET_KEY);
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setProtocol(Protocol.HTTP);
        clientConfig.setConnectionTimeout(60000);
        return new AmazonS3Client(credentials,clientConfig);
    }
    
    public static boolean uploadObject(String bucket,String dir,String fileName,MultipartFile uploadFile){
        boolean rcode = false;
        AmazonS3 client = getS3Client();
        dir = checkDir(bucket, dir, client);
        long length = uploadFile.getSize();
        ByteArrayInputStream bis= null;
        try {
            bis = new ByteArrayInputStream(uploadFile.getBytes());
        } catch (IOException e) {
            logger.error("AWSUtil upload file exception.", e);
        }
        ObjectMetadata metaData = new ObjectMetadata();
        metaData.setContentType("application/octet-stream");
        metaData.setContentLength(length);
        metaData.setContentDisposition("attachment;filename="+fileName);
        PutObjectResult rs = client.putObject(bucket, dir+fileName, bis,metaData);
        String result = rs.getContentMd5();
        if(!StringUtil.isBlank(result)){
            rcode = true;
        }
        return rcode;
    }
    
     public static String checkDir(String bucket,String dir ,AmazonS3 client){
            boolean  isExist =  client.doesBucketExist(bucket);
            if(!isExist){ //如果不存在
                client.createBucket(bucket);
            }
            //创建文件夹
            dir = dir.endsWith("/")?dir:dir+"/";
            isExist = client.doesObjectExist(bucket, dir);
            if(!isExist){
                ObjectMetadata meta = new ObjectMetadata();
                meta.setContentLength(0);
                client.putObject(new PutObjectRequest(bucket,dir,new ByteArrayInputStream(new byte[0]),meta));
            }
            return dir;
     }
     
     
     public static void main(String[] args){
         AmazonS3 client = getS3Client();
         String dir="xiaona.nickName.com/ucpaas/1231323113131-132131/ivr/";
         checkDir("uobject",dir,client);
     }
     
     

    
}
